package com.wisdom.system.api.core.exception;

import com.wisdom.system.entity.out.ResultBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalErrorHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = Exception.class)
    public ResultBody processGlobalException(Exception exception) {
        String defaultMessage;
        if (exception.getCause() != null) {
            defaultMessage = exception.getCause().getMessage();
        } else {
            defaultMessage = exception.getMessage();
        }
        exception.printStackTrace();
        ResultBody result = new ResultBody();
        result.setCode("101");
        result.setMsg(defaultMessage);
        logger.error(defaultMessage);
        return result;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultBody processValidationError(MethodArgumentNotValidException exception) {
        String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        //try {
        //  defaultMessage = new String(defaultMessage.getBytes(), "UTF-8");
        //} catch (Exception ex) {
        //  defaultMessage = "";
        //}
        ResultBody result = new ResultBody();
        result.setMsg(defaultMessage);
        result.setCode("100");
        logger.error(defaultMessage);
        return result;
    }


}
